using System;
using System.Collections.Generic;
using System.Text;

using System.Data;

using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Metadata;

namespace winCRM4QueryBuilder
{
    class clUtility
    {

        /// <summary>
        /// Get Crm Services
        /// </summary>
        /// <param name="crmServerurl"></param>
        /// <param name="organizationname"></param>
        /// <param name="defaultcredentials"></param>
        /// <param name="susername"></param>
        /// <param name="spwd"></param>
        /// <returns></returns>
        public static CrmService GetCrmService(string crmServerurl,
                                               string organizationname,
                                               bool defaultcredentials,
                                               string susername,
                                               string spwd,
                                               string sdomainname)
        {
            CrmService service = new CrmService();
            try
            {
                CrmAuthenticationToken token = new CrmAuthenticationToken();
                token.AuthenticationType = 0;
                token.OrganizationName = organizationname;
                service.CrmAuthenticationTokenValue = token;

                if (!string.IsNullOrEmpty(crmServerurl))
                {
                    UriBuilder builder = new UriBuilder(crmServerurl);
                    builder.Path = "/MSCRMServices/2007/CrmService.asmx";
                    service.Url = builder.Uri.ToString();
                }

                if (defaultcredentials == true)
                {
                    service.UseDefaultCredentials = true;
                }
                else
                {
                    service.Credentials = new System.Net.NetworkCredential(susername, spwd, sdomainname);
                }
                service.CrmAuthenticationTokenValue = token;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Fail(ex.ToString());
            }
            return service;
        }


        /// <summary>
        /// return all entities in crm
        /// </summary>
        /// <returns></returns>
        public DataTable GetAllCrmEntities()
        {
            DataTable mydt = new DataTable();
            DataColumn mycol = new DataColumn("colname");
            mydt.Columns.Add(mycol);
            DataRow myrow;
            foreach (string s in Enum.GetNames(typeof(EntityName)))
            {
                myrow = mydt.NewRow();
                myrow["colname"] = s;
                mydt.Rows.Add(myrow);
            }
            return mydt;
        }


    }
}
